package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String baseDir;

    @RequestMapping("/upload")
    public R<String>upload(MultipartFile file){
        String rootClass = CommonController.class.getResource("/").getPath();
        String dirPath=rootClass+baseDir;
        File dir=new File(dirPath);
        if (!dir.exists()){

            dir.mkdir();
        }

        String originalFilename = file.getOriginalFilename();

        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileName = UUID.randomUUID() + extName;
        try {
            file.transferTo(new File(dir,fileName));
        } catch (IOException e) {
           throw  new SystemException("服务器写入磁盘文件失败",e);
        }
        return R.success(fileName);

    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        String rootClass = CommonController.class.getResource("/").getPath();
        String filePath=rootClass+baseDir +"/"+name;

        InputStream inputStream =null;

        try {
            inputStream= new FileInputStream(filePath);
            IOUtils.copy(inputStream,response.getOutputStream());
        } catch (IOException e) {
        throw new SystemException("获取文件失败",e);
        }
    }



}
